package io.netty.example;

import io.netty.util.concurrent.*;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class NettyFutureTest {

    public static void main(String[] args) {
        System.out.println("current thread: " + Thread.currentThread().isDaemon());

        EventExecutor eventExecutor = new DefaultEventExecutor(new DefaultThreadFactory("promise", true));
        final Promise<String> promise = eventExecutor.newPromise();
        promise.addListener(new GenericFutureListener<Future<? super String>>() {
            @Override
            public void operationComplete(Future<? super String> future) throws Exception {
                System.out.println("complete....");
                if (future.isSuccess()) {
                    System.out.println("future is success, result: " + future.get());
                } else {
                    System.out.println("future is failed, result: " + future.cause());
                }
            }
        });

        Executors.newSingleThreadExecutor(new DefaultThreadFactory("biz", true)).execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("task is running...");
                sleep(800);
                if (promise.isCancelled()) {
                    System.out.println("promise has been canceled...");
                } else {
                    promise.setSuccess("ok");
                }
                System.out.println("biz execute over...");
            }
        });
//        eventExecutor.execute(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("task is running...");
//                sleep(800);
//                if (promise.isCancelled()) {
//                    System.out.println("promise has been canceled...");
//                } else {
//                    promise.setSuccess("ok");
//                }
//                System.out.println("biz execute over...");
//            }
//        });

//        sleep(100);
//        boolean canceled = promise.cancel(true);
//        System.out.println("promise cancel result: " + canceled);

//        Thread.currentThread().interrupt();
//        System.out.println("main thread isInterrupted: " + Thread.currentThread().isInterrupted());

        try {
            promise.sync();
        } catch (InterruptedException e) {
            System.out.println("here...");
            e.printStackTrace();
        }


        System.out.println("main over...");

    }

    private static void sleep(long timeMs) {
        try {
            TimeUnit.MILLISECONDS.sleep(timeMs);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}